#pragma once

#include<iostream>
#include<memory>
#include<unordered_map>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include<mutex>

#include"util.hpp"

typedef websocketpp::server<websocketpp::config::asio> websocket_server;


class online_manager{

    private:

    //游戏大厅的客户端连接管理
    std::unordered_map<uint64_t,websocket_server::connection_ptr> _hall_user;

    //游戏房间的客户端连接
    std::unordered_map<uint64_t,websocket_server::connection_ptr> _room_user;

    std::mutex _mutex;

    public:


    //只要建立websocket连接后才会加入游戏大厅&游戏房间的在线用户管理

    //进入游戏大厅
    void enter_game_hall(uint64_t uid,websocket_server::connection_ptr& conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        
         LOG_INF("加入游戏大厅的uid: %lu ",uid);
        _hall_user.insert(std::make_pair(uid,conn));
    }

    
    //进入游戏房间
    void enter_game_room(uint64_t uid,websocket_server::connection_ptr& conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);

        LOG_INF("加入游戏房间的uid: %lu ",uid);
        _room_user.insert(std::make_pair(uid,conn));
    }

    //退出游戏大厅
    void exit_game_hall(uint64_t uid)
    {
         std::unique_lock<std::mutex> lock(_mutex);
        LOG_INF("退出游戏大厅的uid: %lu ",uid);

        _hall_user.erase(uid);
    }


    //退出游戏房间
    void exit_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        LOG_INF("退出游戏房间的uid: %lu ",uid);
        _room_user.erase(uid);
    }

    //判断用户是否存在

    bool is_in_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it=_hall_user.find(uid);
        if(it==_hall_user.end())
        {
            return false;
        }
        return true;
    }

    bool is_in_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it=_room_user.find(uid);
        if(it==_room_user.end())
        {
            return false;
        }
        return true;

    }


    //通过用户id查询游戏房间中相应的用户连接

    websocket_server::connection_ptr get_conn_from_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it=_hall_user.find(uid);
        if(it==_hall_user.end())
        {
            return websocket_server::connection_ptr();
        }
        return it->second;
    }

    websocket_server::connection_ptr get_conn_from_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it=_room_user.find(uid);
        if(it==_room_user.end())
        {
            return websocket_server::connection_ptr();
        }
        return it->second;
    }



};